<?php

class RecuperacionController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	
	public function filters() {
        return array(array('CrugeAccessControlFilter'));
    }
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','selectfacultad','selectcarrera', 'selectperiodo','clases'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Recuperacion;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Recuperacion']))
		{
			$model->attributes=$_POST['Recuperacion'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id_recuperacion));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Recuperacion']))
		{
			$model->attributes=$_POST['Recuperacion'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id_recuperacion));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Recuperacion');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Recuperacion('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Recuperacion']))
			$model->attributes=$_GET['Recuperacion'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Recuperacion the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Recuperacion::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Recuperacion $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='recuperacion-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionSelectfacultad(){
		if(Yii::app()->getRequest()->isAjaxRequest){
			Yii::log(CVarDumper::dumpAsString(Yii::app()->getRequest()),'info','Recuperacion');
			
			$fid = Yii::app()->getRequest()->getParam('facultad',0);
			
			$soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
			$carreras = $soapClient->listarCarreras();
			$array = array();
			foreach($carreras as $carrera){
				if($carrera['org_unid_acad_id'] == $fid){
					$array[$carrera['org_carrera_id']] = $carrera['nombre'];	
				}
			}

			$t = CHtml::tag('option', array('value'=>''), CHtml::encode('Por favor seleccione...'), true);
			foreach($array as $valor => $nombreCarrera){
				$t = $t.CHtml::tag('option', array('value'=>$valor), CHtml::encode($nombreCarrera), true);
			}
			echo $t;
		}
	}
	
	public function actionSelectcarrera(){
		if(Yii::app()->getRequest()->isAjaxRequest){
			Yii::log(CVarDumper::dumpAsString(Yii::app()->getRequest()),'info','Recuperacion');
			
			$soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
			$periodos = $soapClient->listarPeriodos();
			$array = array();
			foreach($periodos as $periodo){
				$array[$periodo['cal_periodo_lectivo_id']] = $periodo['nombre'].' - '.$periodo['anho_academico'];
			}
			
			if(count($array) == 0){
				$t = CHtml::tag('option', array('value'=>''), CHtml::encode('No se encuentran resultados'), true);
			}else{
				$t = CHtml::tag('option', array('value'=>''), CHtml::encode('Por favor seleccione...'), true);
				foreach($array as $valor => $nombrePeriodo){
					$t = $t.CHtml::tag('option', array('value'=>$valor), CHtml::encode($nombrePeriodo), true);
				}
			}
			echo $t;
		}
	}
	
	public function actionSelectperiodo(){
		if(Yii::app()->getRequest()->isAjaxRequest){
			Yii::log(CVarDumper::dumpAsString(Yii::app()->getRequest()),'info','Recuperacion');
			
			$cid = Yii::app()->getRequest()->getParam('carrera',0);
			$pid = Yii::app()->getRequest()->getParam('periodo',0);

			$soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
			$materias = $soapClient->listarMaterias();
			$cursos = $soapClient->listarCursos();
			
			$array = array();
			foreach($materias as $materia){
				if($materia['org_carrera_id'] == $cid){
					Yii::log(CVarDumper::dumpAsString($materia),'info','Recuperacion Controller');
					foreach($cursos as $curso){
						if($curso['cal_periodo_lectivo_id'] == $pid){
							if($curso['pe_asignatura_id'] == $materia['pe_asignatura_id']){
								$array[$curso['prg_curso_id']] = $materia['nombre'];	
							}
						}
					}
				}
			}
			
			if(count($array) == 0){
				$t = CHtml::tag('option', array('value'=>''), CHtml::encode('No se encuentran resultados'), true);
			}else{
				$t = CHtml::tag('option', array('value'=>''), CHtml::encode('Por favor seleccione...'), true);
				foreach($array as $valor => $nombreCurso){
					$t = $t.CHtml::tag('option', array('value'=>$valor), CHtml::encode($nombreCurso), true);
				}
			}
			echo $t;
		}
	}
	
	public function actionClases(){
		if(Yii::app()->getRequest()->isAjaxRequest){
			Yii::log(CVarDumper::dumpAsString(Yii::app()->getRequest()),'info','Recuperacion Controller');
			
			$cid = Yii::app()->getRequest()->getParam('idCurso',0);
			$edit = Yii::app()->getRequest()->getParam('edit',0);
			$rid = Yii::app()->getRequest()->getParam('idRecuperacion',0);
			
			$soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
			$horas = $soapClient->getCantHoraMateriaGeneral($cid);
			$curso = $soapClient->getCurso($cid);
			$periodo = $soapClient->getPeriodo($curso['cal_periodo_lectivo_id']);
			
			$desde = $periodo['fecha_desde'];
			$hasta = $periodo['fecha_hasta'];
			
			Yii::log(CVarDumper::dumpAsString($horas),'info','Recuperacion Controller');
			
			$r = '';
			foreach($horas as $key => $array){
				$r .= $key.',';
			}
			Yii::log(CVarDumper::dumpAsString($r),'info','Recuperacion Controller');
			$r = substr($r,0,strlen($r)-1);
			
			$fechas = Recuperacion::model()->findAllByAttributes(array('id_curso'=>$cid));
			if($edit){
				$fechaEdit = Recuperacion::model()->findByPk($rid);
				$fechaEdit = $fechaEdit['fecha_clase'];
				Yii::log("Fecha edit: $fechaEdit",'info','Recuperacion COntroller');
			}
			$f = '';
			foreach($fechas as $fecha){
				if($edit && $fecha->fecha_clase == $fechaEdit){
					continue;
				}
				$f .= '"'.$fecha->fecha_clase.'",';	
			}
			Yii::log(CVarDumper::dumpAsString($f),'info','Recuperacion Controller');
			$f = substr($f,0,strlen($f)-1);
			
			header("Content-type: application/json");
			echo '{"dias": ['.$r.'], "fechas": ['.$f.'], "minDate":	"'.$desde.'", "maxDate": "'.$hasta.'"}';
		
		}
	}
	
	public function getNombreCurso($idCurso)
	{
		$soapClient = new SoapClient(Yii::app()->getParams()->webServiceUrl);
		$curso = $soapClient->getCurso($idCurso);
		$materia = $soapClient->getMateria($curso['pe_asignatura_id']);
		return $materia['nombre'];
	}
}
